package com.cheetah.seckill.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.api.R;
import com.cheetah.seckill.entity.Order;
import com.cheetah.seckill.entity.Seckill;
import com.cheetah.seckill.mapper.SeckillMapper;
import com.cheetah.seckill.service.SeckillService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/seckill")
public class SeckillController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private SeckillMapper seckillMapper;
    @Value("${project.path}")
    private String projectPath;

    @RequestMapping("/start")
    public R start(long id) {
        Order order = newOrder(id);
        this.rocketMQTemplate.convertAndSend("topic_order", order);
        return R.ok("秒杀成功");
    }

    @RequestMapping("/list")
    public Object list() {
        return this.seckillMapper.selectList(new QueryWrapper<>());
    }

    @RequestMapping("/createHtml")
    public Object createHtml(Long id, HttpSession session) throws Exception {
        Seckill seckill = this.seckillMapper.selectById(id);
        Configuration conf = new Configuration();
        conf.setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(), "/static/template");

        Template template = conf.getTemplate("goods.flt");
        File file= new File(projectPath + seckill.getId()+".html");
        Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        template.process(seckill, writer);
        return R.ok("");
    }

    Order newOrder(long id) {
        Order order = new Order();
        order.setId(IdWorker.getId());
        order.setSeckillId(id);
        return order;
    }
}
